//
//  AQRImageZoomView.m
//  IfengNews
//
//  Created by Ryan on 13-5-13.
//
//

#import "AQRImageZoomView.h"
//#import "NewsPhotoSlidesViewController.h"
#import "AQRSlidesView.h"
#import "UIImageView+WebCache.h"

@interface AQRImageZoomView()

@property (nonatomic,strong) NSString *imageURL;
@property (nonatomic,strong) UIView *scrollContentView;
@property (nonatomic,strong) UIImageView *bgview;
@property (nonatomic,strong) NSDictionary *source;
@end

@implementation AQRImageZoomView
@synthesize imageView,tagDelegate;

- (id)init{
    self=[super init];
    if(self){
        NSAssert(false, @"不要用这个，必须有frame参数");
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate=self;
        self.fromRect=CGRectZero;
        [self initImageView];
        _dic_temp = [NSDictionary new];
        _arr_temp = [NSArray new];
        _bannerTag = 0;
    }
    return self;
}

- (void)tapSelect:(SEL) selector target:(id)target{
    UITapGestureRecognizer *recognizer=[[UITapGestureRecognizer alloc] initWithTarget:target action:selector];
    recognizer.numberOfTapsRequired=1;
    recognizer.numberOfTouchesRequired=1;
    [self.scrollContentView addGestureRecognizer:recognizer];
}


- (void)dealloc{
    //self.imageView.delegate=nil;
}

//- (void)doResponse:(IfengData_Response *)response{
//    if(response.responseCode==0 &&
//       response.responseObject &&
//       [response.responseObject isKindOfClass:[UIImage class]]&&
//       [self.imageURL isEqualToString:response.url]){
//        UIImage *image=(UIImage *)response.responseObject;
//        CGSize imageSize=image.size;
//        CGSize targetSize=self.scrollContentView.bounds.size;
//        float scaleW=imageSize.width/targetSize.width;
//        float scaleH=imageSize.height/targetSize.height;
//        CGRect rect=CGRectZero;
//        if(scaleW>scaleH){
//            rect.size.width=targetSize.width;
//            rect.size.height=image.size.height/scaleW;
//        }else{
//            rect.size.height=targetSize.height;
//            rect.size.width=image.size.width/scaleH;
//
//        }
//        self.imageView.frame=rect;
//        float fillrange=rect.size.height/targetSize.height;
//        float bitheight=fillrange<0.7?60.0*(1-fillrange):0.0f;
//       
//        
//        [self.imageView setCenter:CGPointMake(targetSize.width/2.0f, targetSize.height/2.0f-bitheight)];
//        initFrame=self.imageView.frame;
//        self.imageView.image=image;
//        self.bgview.hidden=YES;
//         self.maximumZoomScale = 3.0f;
//    }
//    else{
//      self.imageURL = nil;
//    }
//}


- (void)doImage:(UIImage *)image{
  
    CGSize imageSize=image.size;
    CGSize targetSize=self.bounds.size;
    
    float scaleW=imageSize.width/targetSize.width;
    float scaleH=imageSize.height/targetSize.height;
    CGRect rect=CGRectZero;
    if(scaleW>scaleH){
        rect.size.width=targetSize.width;
        rect.size.height=image.size.height/scaleW;
    }else{
        rect.size.height=targetSize.height;
        rect.size.width=image.size.width/scaleH;
        
    }
    self.imageView.frame=rect;
    
    float fillrange=rect.size.height/targetSize.height;
    float bitheight=fillrange<0.7?60.0*(1-fillrange):0.0f;
    
    
    [self.imageView setCenter:CGPointMake(targetSize.width/2.0f, targetSize.height/2.0f-bitheight)];
    initFrame=self.imageView.frame;
    self.imageView.image=image;
    self.bgview.hidden=YES;
    self.maximumZoomScale = 3.0f;
    
    if(!CGRectEqualToRect(self.fromRect, CGRectZero)){
        CGRect tframe=self.imageView.frame;
       
        self.imageView.frame=self.fromRect;
        [UIView animateWithDuration:0.2 animations:^{
            self.imageView.frame=tframe;
        }];
    }
}

- (void)doError{
    self.imageURL = nil;
}

- (void)setImgUIViewContentMode:(UIViewContentMode)mode{
    self.imageView.contentMode=mode;
}

- (void)setImageUrl:(NSString *)url block:(void (^)(UIImage *img))block{
    if(url && ((![url isEqualToString:self.imageURL]) || self.imageView.image==nil)){
        __weak typeof(self) me=self;
        [self setImageNil];
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:url]
                          placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                              if(error){
                                  [me doError];
                                  if(block){
                                      block(nil);
                                  }
                              }else{
                                  [me doImage:image];
                                  if(block){
                                      block(image);
                                  }
                              }
                          }];
        
        self.imageURL=url;
    }
    else{
        self.imageURL=nil;
        [self setImage:self.imageView.image];
        if(block){
            block(self.imageView.image);
        }
    }

}


- (void)setImageUrl:(NSString *)url{
    
    [self setImageUrl:url block:nil];
}

- (void)setImage:(UIImage *)aimage{
    
  CGSize imageSize=aimage.size;
  CGSize targetSize=self.bounds.size;
    
  float scaleW=imageSize.width/targetSize.width;
  float scaleH=imageSize.height/targetSize.height;
  CGRect rect=CGRectZero;
  if(scaleW>scaleH){
    rect.size.width=targetSize.width;
    rect.size.height=aimage.size.height/scaleW;
  }else{
    rect.size.height=targetSize.height;
    rect.size.width=aimage.size.width/scaleH;
    
  }
  self.imageView.frame=rect;
  float fillrange=rect.size.height/targetSize.height;
  float bitheight=fillrange<0.7?60.0*(1-fillrange):0.0f;
  
  
  [self.imageView setCenter:CGPointMake(targetSize.width/2.0f, targetSize.height/2.0f-bitheight)];
  initFrame=self.imageView.frame;
  self.imageView.image=aimage;
  self.bgview.hidden=YES;
  self.maximumZoomScale = 3.0f;

/*
    self.imageView.image=aimage;
    self.bgview.hidden=YES;
    self.maximumZoomScale = 3.0f;
 */
}

- (void)setImageNil{
  
    self.imageView.image=nil;
    self.bgview.hidden=NO;
    self.maximumZoomScale = 1.0f;
  
}
-(void)setImageUrlNil{
  self.imageURL = nil;
}
- (UIImage *)image{
    return self.imageView.image;
}


- (void)initImageView{
    
    self.scrollContentView=[[UIView alloc] init];
    self.bouncesZoom = YES;
    self.minimumZoomScale = 1.0;
    self.maximumZoomScale = 1.0;
    self.decelerationRate = 0.0f;
    //self.scrollContentView.frame=CGRectMake(0, 0, self.frame.size.width*2.5f, self.frame.size.height*2.5f);
    self.scrollContentView.frame=self.bounds;
    self.scrollContentView.backgroundColor=[UIColor clearColor];
    self.scrollContentView.userInteractionEnabled =YES;
    self.imageView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.imageView=[[UIImageView alloc] init];
    //self.imageView.delegate=self;
    imageView.userInteractionEnabled = YES;
//    UIImage *image=[UIImage imageNamed:@"image_detail_loadingorloading_failure.png"];
//    CGSize size=image.size;
//    self.bgview=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.width/2.0f, size.height/2.0f)];
//    self.bgview.image=image;
//    [self.bgview setCenter:CGPointMake(self.bounds.size.width/2.0f, self.bounds.size.height/2.0f)];
//    [self.scrollContentView addSubview:self.bgview];
    [self.scrollContentView addSubview:self.imageView];
    [self addSubview:self.scrollContentView];
    NSAssert(self.frame.size.width!=0|self.frame.size.height!=0, @"frame 不能是0啊");
    self.backgroundColor=[UIColor clearColor];
//     miniScale = self.frame.size.width / self.scrollContentView.frame.size.width;
//    [self setMinimumZoomScale:miniScale];
//    [self setZoomScale:miniScale];
    [self setZoomScale:1];
    currentScale=1;
    
     }

- (void)updateFrameWithRect:(CGRect)_rect
{
    initFrame = _rect;
    self.scrollContentView.frame = _rect;
    [self.bgview setCenter:CGPointMake(_rect.size.width/2.0f, _rect.size.height/2.0f)];
    [self resetScale];
}

- (void)resetScale{
   
    [self setZoomScale:1];
    self.imageView.frame = initFrame;
    currentScale = 1;
}


#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if (self.imageView.hidden) {
        return nil;
    }
    
    return self.scrollContentView;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
    if(scale==1){
        self.imageView.frame=initFrame;
    }else{
   
    }
    //[scrollView setZoomScale:scale animated:NO];
    currentScale=scale;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.imageView.hidden) {
        return;
    }
}

//- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//   // [self checkYscroll];
//}
//
//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//    [self checkYscroll];
//}


- (void)checkYscroll{
//    NSLog(@"%f",self.contentOffset.y);
//    NSLog(@"%f",imageView.frame.origin.y);
//    float scalsY=(self.imageView.frame.origin.y-self.contentOffset.y)*currentScale;
//    if(scalsY>150){
//        float cy=self.imageView.frame.origin.y-(150.0f/currentScale);
//        CGPoint point=self.contentOffset;
//        point.y=cy;
//        [self setContentOffset:point animated:YES];
//    }else if(scalsY<-290){
//        float cy=self.imageView.frame.origin.y-(-290.0f/currentScale);
//        CGPoint point=self.contentOffset;
//        point.y=cy;
//        [self setContentOffset:point animated:YES];
//
//    }
}



@end
